var productdata;
var curhashpath;
$(function(){
	loadProducts(getQueryString("showtype"));
	$('#J_sorts li').click(function(){
		$('#J_sorts li').removeClass("cur");
		$(this).addClass("cur");
		sort();
	})
	$('.J_showBtn').click(function(){
		$(this).parents('.row').toggleClass('expand')		
	})
	$('.J_toClss').click(function(){
		$(this).toggleClass('cur');
		query(1);
	})
	
	loadMaylike(6,loadMaylikeok);
	if(getQueryString("showtype")=='list')$('#J_cuts li').eq(1).addClass("cur");
	else $('#J_cuts li').eq(0).addClass("cur");
})
function showlisttype(type){
	$("input[name='showtype']").val(type);
	showProducts(type);
	if(type=='list'){$('#J_cuts li').removeClass("cur");$('#J_cuts li').eq(1).addClass("cur");}
	else{$('#J_cuts li').removeClass("cur");$('#J_cuts li').eq(0).addClass("cur");}
}

//var productLoadingHtml = "<div style='width: 100%;min-height: 300px;line-height: 300px;text-align: center;'><img src='"+ctx+"/website/images/blue_loading.gif'></div>";
var productNoDataHtml = "<div style='width: 100%;min-height: 300px;line-height: 300px;text-align: center;'><p>抱歉，暂未找到相关商品，请尝试其它条件！</p></div>";
function showProducts(showtype){

    //$("#productspanel").html(productLoadingHtml);

    var h='';
    if(showtype=='list')h=getProductHtml_list();
    else h=getProductHtml_big();

    if(productdata&&productdata.length>0){
        $("#productspanel").html(h);
    } else {
        $("#productspanel").html(productNoDataHtml);
    }

}


function loadProducts(showtype){
	var parm=getQueryParm();
	$w.httpRequest({
		url:apiroot+"/product/loadproducts",
		data:{"classcode":parm.clscode,"attritems":parm.attritems,"pno":$("[name='pageno']").val(),"ordertype":parm.ordertype,"orderby":parm.orderby,"instock":parm.instock,"querylike":parm.querylike,"floorid":parm.floorid,"flooritemid":parm.flooritemid},
		ok:function(ret){
			productdata=ret.Data.products;
			for(var i=0;i<productdata.length;i++){
				if(productdata[i].b_chanjia && productdata[i].b_chanjia.length>11)productdata[i].b_chanjia=productdata[i].b_chanjia.substr(0,11)+"...";
			}
			showProducts(showtype);
			$("#resultCount").html("共找到<font style='color:red;padding:0 3px'>"+ret.Data.resultcount+"</font>件商品");
			$("#pageingcount").text(" 共"+ret.Data.pagecount+"页，到第");
			var pagelist=$("#pagelist");

			for(var i=0;i<ret.Data.pagelist.length;i++) {
                var bean = ret.Data.pagelist[i];
                var h = '';
                if (bean.type == 1) {
                    h = "<a href='javascript:gopage(" + bean.pageno + ");' class='page-btn'>上一页</a>";
                    pagelist.append(h);

                    var prevPageno = bean.pageno;
                    $("#btnListPrev").click(function () {
                        gopage(prevPageno);
                    });

                } else if (bean.type == 2) {
                    h = "<a href='javascript:gopage(" + bean.pageno + ");' class='page-btn'>下一页</a>";
                    pagelist.append(h);

                    var nextPageno = bean.pageno;
                    $("#btnListNext").click(function () {
                        gopage(nextPageno);
                    });

                } else if (bean.type == 3) {

                    h = "<a href='javascript:;'>...</a>";
                    pagelist.append(h);
                } else {
                    h = "<a href='javascript:gopage(" + bean.pageno + ");' " + (bean.cur ? "class='cur'" : "") + ">" + bean.pageno + "</a>";
                    pagelist.append(h);

                    if(bean.cur){
                        $("#txtListPageInfo").html("<i class='cur'> "+ bean.pageno +" </i> / <i> "+ ret.Data.pagecount +" </i>");
                    }

                }
            }
		}
	});
}


function selCls(obj){
	$(obj).parent().children().removeClass("cur");
	$(obj).addClass("cur");
	$("[name='clscode']").val($(obj).attr("code"));
	query(1);
}
function removecls(code){
	var n=code.lastIndexOf(".");
	$("[name='clscode']").val(code.substr(0,n));
	query(1);
}
function selattr(obj){
	$(obj).parent().children().removeClass("cur");
	$(obj).addClass("cur");
	query(1);
}
function removeattr(id){
	$("[itemid='"+id+"']").removeClass("cur");
	if(id.indexOf("floor_")==0){$("[name='floorid']").val('');$("[name='flooritemid']").val('');}
	else if(id.indexOf("flooritem_")==0)$("[name='flooritemid']").val('');
	query(1);
}
function query(n){
	var parm=getQueryParm();
	var url=ctx+"/product/list?clscode="+parm.clscode+"&attritems="+parm.attritems+"&ordertype="+
		parm.ordertype+"&orderby="+parm.orderby+"&instock="+
		parm.instock+"&floorid="+parm.floorid+"&flooritemid="+
		parm.flooritemid+"&pno="+n+"&querylike="+encodeURIComponent(parm.querylike)+"&showtype="+parm.showtype;
	if(curhashpath)url+="#!"+curhashpath;
	window.location.href=url;
}
function getQueryParm(){
	var parm=new Object();
	var attritems="";
	$(".attrs").each(function(){
		if($("a.cur",$(this)).length>0){
			if(attritems!="")attritems+=",";
			attritems+=$("a.cur",$(this)).attr("itemid");
		}
	})
    parm.showtype=$("[name='showtype']").val()=="big"?"big":"list";
    parm.clscode=$("[name='clscode']").val();
	parm.attritems=attritems;
	var sort=$("#J_sorts li.cur");
	parm.ordertype=sort.attr("ordertype");
	parm.orderby=sort.attr("orderby");
	if($(".J_toClss").get(0).className.indexOf("cur")!=-1)parm.instock=1;
	else parm.instock=0;
	parm.querylike=$("[name='querylike']").val();
	parm.floorid=$("[name='floorid']").val();
	parm.flooritemid=$("[name='flooritemid']").val();
	return parm;
}
function replaceHtmlFileserver(html){

    if(html){

		var sourceHtml = html;
		var fsIndex = -1;
		var targetHtml = "";
		do{
            fsIndex = sourceHtml.indexOf(fileserver);
            if( fsIndex >= 0 ){
            	if( fsIndex != 0 ){
                    targetHtml += sourceHtml.substr( 0 , fsIndex );
                }
                targetHtml += getRandomFileserver();
            	if( ( fsIndex + fileserver.length ) < ( sourceHtml.length - 1 ) ){
                    sourceHtml = sourceHtml.substring( fsIndex + fileserver.length );
                }
			} else {
                targetHtml += sourceHtml;
			}
		} while ( fsIndex >= 0 );

		return targetHtml;

	}
	return html;
}
//大图
function getProductHtml_big(){
	var html='<ul class="list-row-container">';
	template.helper("titlelen", function(a){
		if(a.length>16)return a.substr(0,16)+"...";
		else return a
	});
	html+=template('productHtml_big', {ctx:ctx,fileserver:fileserver,isuserauth:isuserauth,islogin:islogin,list:productdata});
    html+="<ul>";

    var newHtml = replaceHtmlFileserver(html);
	return newHtml;
}
//列表
function getProductHtml_list(){
	var html='<ul class="list-row-container">';
	html+=template('productHtml_list', {ctx:ctx,fileserver:fileserver,isuserauth:isuserauth,islogin:islogin,list:productdata});
	html+="<ul>";

    var newHtml = replaceHtmlFileserver(html);
    return newHtml;
}
function addamount(obj){
  var txt=$("[name='amount']",$(obj).parent());
  var n=parseInt(txt.val());
  n++;
  txt.val(n);
  inputAmount(txt);
}
function lessenamount(obj){
  var txt=$("[name='amount']",$(obj).parent());
  var n=parseInt(txt.val());
  n--;
  txt.val(n);
  inputAmount(txt);
}
function addtocart(event,pid,obj){
	if($(obj).hasClass('can')){
		var url=ctx+"/order/addToCart?pid="+pid+"&amount="+$("[name='amount']",$("[pid='"+pid+"']")).val();
		//window.open(url);
        $w.addCartItem(event,obj,url);
	}
}

function addOften(pid,obj){
	  $w.httpRequest({
		url:apiroot+"/order/addOften",
		data:{"priceid":pid},
		ok:function(ret){
			$(obj).text("已加入");
		}
	})
}

function gopage(n){
	query(n);
}
function topageclick(){
	if($("[name='topagenum']").val()!="")
		query($("[name='topagenum']").val());
}
function sort(){
	var sort=$("#J_sorts li.cur");
	if(sort.attr("ordertype")=='3'){
		if(sort.attr("orderby")=="0")sort.attr("orderby","1");//降序
		else sort.attr("orderby","0");//顺序
	}
	query(1);
}
function loadMaylikeok(datas){

	  var panel=$("#maylike");
	  for(var i=0;i<datas.list.length;i++){
		  var data=datas.list[i];
		  var h='<li class="Related-item">'
		      +'<div class="Related-pic"><a href="'+ctx+'/product/info?priceid='+data.id+'" target="_blank"><img src="'+getRandomFileserver()+data.photo+'" width="130" height="130" onerror="this.src=\''+ctx+'/website/images/noimg.jpg\'"/></a></div>'
		      +'<div class="Related-text">';
		  	if(isuserauth && islogin)h+='<p><strong>￥'+data.price+'</strong></p>';
		  	else if(!islogin)h+='<p><font class="red">登录可见</font></p>';
		  	else h+='<p><font class="red">审核通过可见</font></p>';
		    h+='<p><a href="'+ctx+'/product/info?priceid='+data.id+'" target="_blank">'+data.productname+' '+data.name+' '+(data.b_guige || '')+'</a></p>'
		      +'</div>'
		      +'</li>';
		  panel.append(h);
	  }
}